<template>
  <el-dialog title="员工导入" :visible="visible" width="500px" @close="onCloseDialog">
    <el-row type="flex" justify="center">
      <el-upload
        ref="uploadRef"
        action
        drag
        accept=".xlsx,.xls"
        :http-request="onUploadFile"
        :limit="1"
        :show-file-list="false"
      >
        <i class="el-icon-upload" />
        <div class="el-upload__text">将文件拖到此处，或<em slot="trigger">点击上传</em></div>
      </el-upload>
    </el-row>
    <el-row type="flex" justify="center" style="margin-top: 20px;">
      <el-button type="primary" style="margin-right: 20px;" @click="onDownloadTemplate">
        下载导入模版
      </el-button>
      <el-button size="middle" @click="onCloseDialog">取消</el-button>
    </el-row>
  </el-dialog>
</template>

<script>
import { downloadExcelTemplateAPI, importEmployeeExcelAPI } from '@/api/employee'
import FileSaver from 'file-saver'

export default {
  name: 'ImportExcel',
  data() {
    return {
      visible: false
    }
  },
  methods: {
    // 打开弹窗
    open() {
      this.visible = true
    },
    // 关闭弹窗
    onCloseDialog() {
      this.visible = false
    },
    // 下载模板
    async onDownloadTemplate() {
      const loading = this.$message({
        type: 'info',
        message: '正在下载...',
        duration: 0
      })
      const template = await downloadExcelTemplateAPI()
      FileSaver.saveAs(template, '员工信息导入模板.xlsx')
      loading.close()
      this.$message({ type: 'success', message: '下载成功!' })
    },
    // 上传员工信息excel
    async onUploadFile(item) {
      const file = item.file
      // 将文件对象添加到formdata中
      const data = new FormData()
      data.append('file', file)
      try {
        // 上传员工信息
        await importEmployeeExcelAPI(data)
        // 提示上传成功
        this.$message({ type: 'success', message: '上传成功!' })
        // 通知父组件，上传成功，刷新员工列表
        this.$emit('uploadSuccess')
        // 关闭弹窗
        this.visible = false
      } catch (error) {
        // 上传失败
      } finally {
        // 清空上传组件
        this.$refs.uploadRef.clearFiles()
      }
    }
  }
}
</script>

<style>

</style>
